var resetClickListener = function($) {

    $('.item-wrap').click(function(event) {

        //imgBig
        var itemId  = $(this).children(".inputItemId").attr("value");
        //console.log("查看大图>>itemId为>>>"+itemId);
        //alert("查看大图>>>>>"+itemId);

        if (itemId !== undefined)
            showBigImg(itemId);
    });


    $('.dishContent').click(function(event) {
        //imgBig
        var itemId  = $(this).children(".inputItemId").attr("value");
        var name  = $(this).next(".name").attr("value");
        //console.log("name>>>>>"+$(this).prev(".name").html());

        var desc = " &nbsp; &nbsp; &nbsp; &nbsp;黄焖鸡米饭又叫香鸡煲，浓汁鸡煲饭，是鲁菜名吃。是源自山东济南天桥区的传统名吃，属于鲁菜系。该特色小吃做成后色香味美，口感鲜嫩透味不粘腻，香味浓郁。";      //TODO:
        //alert("详情");
        if (itemId !== undefined)
            showDishDesc(itemId, name, desc);
        //阻止事件冒泡
        return false;
    });


    //关闭按钮
    $('#closeReveal_2').click(function(){
        //alert("无法关闭？？");
        //$('#header-login').trigger('reveal:close');
        //弹出层关闭
        $('.close-reveal-modal').trigger('click');
    });

    //关闭按钮
    $('#myCloseReveal').click(function(){
        //弹出层关闭
        $('.close-reveal-modal').trigger('click');
    });

    //购物车总高
    var zh=$(window).height();
    var zw=$(window).width();
    var shopHeight=zh-100;
    $(".shop-body").height(shopHeight);
    var mRight='0px';

    //默认显示购物车
    $(".shop-cart").css("right","0px");
    $(".shop-bottom").css("right","0px");

    //购物车相关
    setTotalPrice();
    //清空购物车
    $(document).on('click','.shop-clear',function(){
        clearCart();
    });
    //加
    $(document).on('click','.plus',function(){
        var itemId=$(this).parents('.shop-item').attr('item-id');
        addCart(itemId);
    });
    //减
    $(document).on('click','.minus',function(){
        var itemId=$(this).parents('.shop-item').attr('item-id');
        deleteCart(itemId);
    });

    //飞入购物车
    $('.orderNow').click(function(e){
        var itemId=$(this).parents(".menu-item").attr("item-id");
        var explorer =navigator.userAgent ;
        var startX;
        var startY;
        var spd;
        if (explorer.indexOf("MSIE") >= 0) {  //ie
            startX=e.clientX+12;
            startY=e.clientY-10;
            spd=1.5;
        }else if(explorer.indexOf("Firefox") >= 0){ //Firefox
            startX=e.clientX;
            startY=e.clientY;
            spd=1.2;
        }else{ //其他
            startX=e.originalEvent.x;
            startY=e.originalEvent.y;
            spd=1.2;
        }
        fly(startX,startY,itemId,spd);//飞入动画

        //通过return false 阻止冒泡
        return false;
    });

    //结算按钮
    $('#cart-pay').click(function(event) {
        var userId=$.cookie('userId');

        //if(userId){ //已登录
        //     location.href="order_confirm_new.html";
        //}else{
        //    $('#header-login').trigger('click');
        //}

        submitOrder();          //TODO:订单结算

    });


    //结算按钮
    $('#cart-pay-bottom').click(function(event) {
        var userId=$.cookie('userId');
        //TODO:
        //if(userId){ //已登录
        //     location.href="order_confirm_new.html";
        //}else{
        //    $('#header-login').trigger('click');
        //}

        submitOrder();           //TODO:订单结算
    });



    //弹出已经下单商品
    $('#cal_bottom').click(function(event) {
        console.log("点击>>>");
        //alert("美柚其实还可以啊");

        //弹出
        $('#id-myOrderedDish').trigger('click');
    });




    //左侧点击切换分类
    $('.leftmenu-item a').click(function(){
        //变样式
        $(this).parents('.leftmenu').find('.leftmenu-item').removeClass('active');
        $(this).parent().addClass('active');
        //变菜品
        var i=$(this).parents('dd').attr('id');
        $('.menu-wrap').hide();
        var m="#"+i.replace('i','m');
        console.log("看下它是怎么替换的>>>"+m);
        $(m).fadeIn(600);
    });

};

//---------------------------------------------------------------
(function($){
    //resetLayout($);

    //购物车总高
    var zh=$(window).height();
    var zw=$(window).width();
    var shopHeight=zh-100;
    $(".shop-body").height(shopHeight);
    var mRight='0px';

    //默认显示购物车
    $(".shop-cart").css("right","0px");
    $(".shop-bottom").css("right","0px");
})(jQuery);


function showBigImg(itemId) {
    var index = layer.load();
    $.ajax({
        type:"get",
        url:imgBig+"?id="+itemId,
        //url:"testData.json",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("查看大图失败");
            layer.close(index);
        },
        data: {},
        dataType: "json",
        success:function(data) {
            //console.log("查看大图返回的data>>>"+data.toString);
            console.log(data);
            dialog.showPhoto(data);
            layer.close(index);
        }
    });
}



    function  submitOrder() {
        console.log("提交订单");
        var tableNum;                               //选中的值
        var shopId = $.cookie('shopId');


        if (shopId) {
            tableNum = $.cookie('table' + shopId);
        }
        if (!tableNum) {  //TODO:有几个桌子需要动态获取
            //alert("下单失败：没有选择桌号");
            //先清空购物车，再跳转回首页
            // clearCart();
            location.href="place.html";
            return;
        }

        location.href="order_confirm_new.html";

        return;

        // var arr = tableNum.split(',');
        // //得到所有菜品
        // //console.log("提交前检查shopId>>"+shopId);
        // if(shopId){
        //     var arrObj=selectAll(shopId);
        //
        //     if(arrObj){
        //         var rs = new Object();
        //         var dishs = new Array();
        //         for(var i=0;i<arrObj.length;i++){
        //             var dish = {};
        //             var itemId=arrObj[i].itemId;
        //             var name=hexToString(arrObj[i].name);
        //             var count=arrObj[i].count;
        //             var price=arrObj[i].price;
        //             var price2=price*count;//单价*个数
        //             dish.itemId = itemId;
        //             dish.name   = name;
        //             dish.count  = count;
        //             dish.price  = price;
        //
        //             dishs.push(dish);
        //         }//for
        //         rs.tableNum = arr;
        //         rs.dishs = dishs;
        //
        //         //console.log(JSON.stringify(rs));
        //         submit(rs);
        //     }//if
        // } else {
        //     alert("没有shopId，请稍后再试");
        // }
    }

    function submit(reqJson) {
        var index = layer.load();
        $.ajax({
            type:"post",
            url:a,
            //url:"testData.json",
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert("生成订单失败：请稍后再试");
                layer.close(index);
            },
            data: reqJson,
            dataType: "json",
            success:function(data) {
                if (!data.code) {
                    alert("生成订单失败：返回格式错误");
                    return;
                }
                switch (data.code) {
                    case 22001 :
                        onSuccessSubmit(data);
                        break;
                    default :
                        alert("生成订单失败");
                        break;
                }
                layer.close(index);
            }
        });
    }

    var onSuccessSubmit = function(data) {
        console.log(data.toString());
        alert("订单生成成功!!");
        location.href="order_confirm_new.html";
    };

    //计算总价
    function setTotalPrice(){
        processShopItem();
        var tmp=0;
        $('.item-price label').each(function(){
            tmp=tmp+parseInt($(this).text());
        });
        $('.bottom-price label').text((tmp)/2);  //TODO:价格之所以除以二的原因在于有两个购物车（侧边/底栏），，，导致总价加了两遍。。。
        console.log("temp>>>>>>"+(tmp)/2);
        if(tmp==0){
            $('.bottom-price label').hide();
            $('.bottom-price').text("菜篮为空");
        }else{ 
            $('.bottom-price').text("总计：￥");
            $('.bottom-price').append("<label>"+(tmp)/2+"</label>");
        }
        //--------------处理空购物车------
        var lc=$('.shop-body').children('.shop-item-wrap').length;
        if(lc<1){
            $('.isnull').show();
            $('.bottom-price').css("width","100%");
            $('.bottom-pay').hide();//隐藏"结算"
        }else{
            $('.isnull').hide();
            $('.bottom-price').css("width","65%");
            $('.bottom-pay').show();//显示"结算"
        }
    }
    //飞入效果
    function fly(startX,startY,itemId,spd){
        var zh=$(window).height();
        var zw=$(window).width();

        var img = flyImg;
        var flyer = $('<img class="u-flyer" src="'+img+'">');
        flyer.fly({
            start: {
                left: startX-10,
                top: startY-10
            },
            end: {
                left:zw-$(".shop-cart").width()+10,
                top: zh-50, 
            }, 
            vertex_Rtop: startY-50,
            speed:spd,
            onEnd: function(){
                addCart(itemId);
                this.destory();
            }
        });
    }

    //初始化购物车
    function initCart(){ 
        var shopId=$.cookie('shopId');
        if(shopId){  
            var arrObj=selectAll(shopId);
            if(arrObj){
                for(var i=0;i<arrObj.length;i++){
                    var itemId=arrObj[i].itemId;
                    var name=hexToString(arrObj[i].name);
                    var count=arrObj[i].count;
                    var price=arrObj[i].price;
                    var price2=price*count;//单价*个数
                    var htmlTxt="<div class='shop-item-wrap'>"
                    +"<div class='shop-item' item-id='"+itemId+"'>"
                    +"<div class='item-name fl'>"
                    +name
                    +"</div>"
                    +"<div class='item-count fl'>"
                    +"<button class='minus'>-</button>"
                    +"<input type='text' value='"+count+"' "
                    +"readonly='readonly' maxlength='3'>"
                    +"<button class='plus'>+</button>"
                    +"</div>"
                    +"<div class='item-price fl' per-price='"+price+"'>"
                    +"￥<label>"+price2+"</label> "
                    +"</div>"
                    +"</div>"
                    +"</div>";
                    $('.shop-body').append(htmlTxt); 
                }
                //--------------底部总价---------
                setTotalPrice();
            }
            
        }
    }





    //添加购物车
    function addCart(itemId){ 
        //buy处的信息
        var obj1=$(".menu-item[item-id='"+itemId+"']");
        var price=obj1.find('.price').attr("item-price");
        //alert("价格>>"+price);
        var name=obj1.find('.name').html();
        //alert("name>>>"+name);
        //console.log("name.>"+name);
        //购物车处的信息
        var obj2=$(".shop-item[item-id='"+itemId+"']");
        //是否已存在
        if(!obj2.html()){
            var htmlTxt="<div class='shop-item-wrap'>"
                +"<div class='shop-item' item-id='"+itemId+"'>"
                +"<div class='item-name fl'>"
                +name
                +"</div>"
                +"<div class='item-count fl'>"
                +"<button class='minus'>-</button>"
                +"<input type='text' value='1' "
                +"readonly='readonly' maxlength='3'>"
                +"<button class='plus'>+</button>"
                +"</div>"
                +"<div class='item-price fl' per-price='"+price+"'>"
                +"￥<label>"+price+"</label> "
                +"</div>"
                +"</div>"
                +"</div>";
            $('.shop-body').append(htmlTxt); 

        } else{
            //-------------个数--------------- 
            var t=obj2.find('.item-count input');
            var count=parseInt(t.val())+1;
            console.log("count>>>"+count);
            t.val(count);
            //-------------单价---------------
            var perPrice=obj2.find('.item-count').siblings('.item-price').attr("per-price");
            //-------------总价---------------
            var price=obj2.find('.item-count').siblings('.item-price').find('label');
            price.text(count*perPrice);
        }
        //--------------底部总价---------
        setTotalPrice();
        //加到cookie
        var shopId=$.cookie('shopId');
        console.log("add>>>shopId>>"+shopId);
        if(shopId){  
            plusItem(shopId,itemId,name,1,price);
        }
    }

    function deleteCart(itemId){
        //购物车处的信息
        var obj=$(".shop-item[item-id='"+itemId+"']");
        var t=obj.find('.item-count input');
        var count=parseInt(t.val())-1;
        if(count<0)count=0;
        t.val(count);
        //-------------单价---------------
        var perPrice=obj.find('.item-count').siblings('.item-price').attr("per-price");
        //-------------总价---------------
        var price=obj.find('.item-count').siblings('.item-price').find('label');
        price.text(count*perPrice);
        //--------------处理0的情况------
        if(count==0){
            obj.parents('.shop-item-wrap').remove();
        } 
        //--------------底部总价---------
        setTotalPrice();
        //减到cookie
        var shopId=$.cookie('shopId');

        if(shopId){   
            minusItem(shopId,itemId);
        }
    }

    function clearCart(){
        //清界面
        $('.shop-item-wrap').remove();
        setTotalPrice();
        //清空cookie
        var shopId=$.cookie('shopId');
        if(shopId){    
            removeAllItem(shopId);
            console.log("清空当前shopId:"+shopId+">>的购物车");
        }
    }


    //适配购物车
    function processShopItem(){
        var shopItemWidth=$(".shop-item").width();
        var itemCountWidth=$(".item-count").width();
        var itemPriceWidth=$(".item-price").width();
        var itemNameWidth=shopItemWidth-itemCountWidth-itemPriceWidth-2;

        $(".item-name").width(itemNameWidth);



        var zw=$(window).width();


        var marginLeft=0;
        //显示两列
        if(zw>=1000){
            $(".item-name").width(itemNameWidth);
            if(zw<1240){
            }else{
            }
        }
        else if(zw<1000){
            $(".item-name").width("45%");
            if(zw<700){
            }else{
            }

            $("#myOrderedDishForm .shop-body").css("height", 240);
        }
    }


    /*
     *  显示菜品详情
     */
    function showDishDesc(itemId, name, desc) {
        //alert("itemId>>"+itemId+"....name>>"+name+"....desc>>"+desc);
        $('.revealTableNum').html(name);
        $('.checkout-tablerow').html(desc);
        //弹出
        $('#dish-desc').trigger('click');
    }



